package ltd.followkba;

import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.view.View;

import com.tencent.bugly.crashreport.CrashReport;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import ltd.advskin.MRAM;
import ltd.advskin.MSKIN;
import ltd.advskin.base.KcListener;
import ltd.advskin.base.SkinActivity;
import ltd.advskin.permission.PermissionsActivity;
import ltd.advskin.permission.PermissionsChecker;
import ltd.advskin.task.TaskSysUpdate;
import ltd.advskin.utils.AdvBitmap;
import ltd.advskin.utils.SysTools;
import ltd.advskin.utils.SysUtils;
import ltd.obbphoto.MOBBW;
import main.MAPI;

import static ltd.advskin.MSKIN.MSTRING;
import static ltd.advskin.MSKIN.MTOAST;

/*

http://www.jianshu.com/p/0cd03c878def?open_source=weibo_search
实现切换主题皮肤功能（类似于众多app中的 夜间模式，主题包等）
http://www.cnblogs.com/punkisnotdead/p/4968851.html
 */

public class BootActivity extends SkinActivity {
    private Timer mTimer;

    private final int[] TabDateTime = new int[]{
            2022, 11, 28,
    };
    public void MLOG(String text) {
        MSTRING(MAPI.GET_LOG_NAME(this) + text);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_boot);
        MRAM.mActivity = this;
        MRAM.mContext = this;
        TaskSysUpdate.logEnable = false;

        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                //Log.e("tag","finish"+mTimer);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        initView();
//                            MLOG(String.format("BootActivity mMyUtils.getSystemIniTime() %d", mMyUtils.getSystemIniTime()));
                    }
                });
            }
        }, 300);
//        CrashReport.initCrashReport(getApplicationContext(), "936e0d869e", true);    // 注册时申请的APP ID
//        SysTools sysTools = new SysTools();
//        sysTools.setSharedString("SysTools.moduleName", getString(R.string.app_name));
//        sysTools.setSharedString("SysTools.appName", "FollowKBa");
//        getBasePermissions();
    }
    private void initView(){
        CrashReport.initCrashReport(getApplicationContext(), "936e0d869e", true);    // 注册时申请的APP ID
        getBasePermissions();
    }

    private void getBasePermissions(){
        PermissionsChecker checker = new PermissionsChecker();
        String[] PERMISSIONS = checker.getBasePermissions();
        if (checker.lacksPermissions(PERMISSIONS)) {
            MSKIN.startPermissionsActivity(PERMISSIONS, new KcListener() {
                @Override
                public void onMessage(Object object) {
                    if (object == null){
                        permissionsSucess();
                    }else {
                        MTOAST("permissions");
                    }
                }
            });
        }else {
            permissionsSucess();
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 0x99) {                  // 权限申请
            if (PermissionsActivity.PERMISSIONS_DENIED == resultCode) {             // 权限未被授予，退出应用
                finish();
            } else if (PermissionsActivity.PERMISSIONS_GRANTED == resultCode) {     // 权限被授予
                permissionsSucess();
            }
        }
    }

    private void permissionsSucess(){
        int fixMode = 0;
        String fixIPAddr = "";
        String appName = "FollowKBa";
        if (false){
//            fixMode = 0x8102; //        0x8102 168 239
            fixMode = 0x8101;       // 232
//            fixMode = 0x8100;       // 231
            fixIPAddr = "114.215.194.168";
        }
//MLOG(String.format("permissionsSucess %s %s ", fixMode, fixIPAddr));
        MSKIN.setStartUp(fixMode, fixIPAddr, appName, "FollowKBa");

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        SysUtils sysUtils = new SysUtils();
        int g4Local_1 = sysUtils.addDateToWord(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH)+1, calendar.get(Calendar.DAY_OF_MONTH));
        int g4Local_2 = sysUtils.addDateToWord(TabDateTime[0], TabDateTime[1], TabDateTime[2]);
        MLOG("BootActivity permissionsSucess A "+g4Local_1 + " "+g4Local_2);
        if (g4Local_1 > g4Local_2){
            finish();
            return;
        }
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
            AdvBitmap.cacheMemory = (byte)0x82;               // 指定分配内存的方式 B7-B4为资源 B3-B0为文件，数值越大分配得越多
        }
//AdvBitmap.isLowMemory = true;
        MOBBW.powerOnAccount();
        MRAM.mTaskSysUpdate = new TaskSysUpdate(appName);

        String[] tabFile = {"c3icon", "pngphoto", "emoji", "arealist", "cchinese", "takemore", "xxx_m00"};         // .md5 及.zip
        String cpuType = MRAM.mTaskSysUpdate.getCpuType();                                          // 先搞清楚自己CPU是什么类型
        tabFile[tabFile.length-1] = String.format("%s_m00", cpuType);                               // 根据CPU的类型自动找对应的文件
        MRAM.mTaskSysUpdate.fileFromServer(tabFile,  false);
        startMainActivity();
    }
    private void startMainActivity(){
        startActivity(new Intent(BootActivity.this, MainActivity.class));   // TestMainActivity
        finish();
    }

    private Boolean CopyAssetsFile(String filename, String des) {
        Boolean isSuccess = true;
        //复制安卓apk的assets目录下任意路径的单个文件到des文件夹，注意是否对des有写权限
        AssetManager assetManager = this.getAssets();

        InputStream in = null;
        OutputStream out = null;
        try {
            in = assetManager.open(filename);
            String newFileName = des + "/" + filename;
            out = new FileOutputStream(newFileName);
            byte[] buffer = new byte[1024];
            int read;
            while ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }
            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;
        } catch (Exception e) {
            e.printStackTrace();
            isSuccess = false;
        }

        return isSuccess;

    }

}
